//
//  cloudsearchmapViewController.m
//  xhtios1.0
//
//  Created by hlt on 15/5/21.
//  Copyright (c) 2015年 hlt. All rights reserved.
//

#import "cloudsearchmapViewController.h"
#import "custompaopaoview.h"
#import "HLTmerchanthomeViewController.h"
#import "HLTzhoubiantuijianyouhuimerchantTableViewController.h"
#import "SliderViewController.h"

//#import "ShopcontentTableViewController.h"
@interface cloudsearchmapViewController ()<BMKLocationServiceDelegate,sliderScrollerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) BMKLocationService *locService ;
@property (strong, nonatomic) CLLocation *location;
@property (strong, nonatomic) NSString *lat;
@property (strong, nonatomic) NSString *log;
@property (strong, nonatomic) NSString *haiba;
@property BOOL biaozhi;

@end

@implementation cloudsearchmapViewController

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden=NO;
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"01登录界面2_r2_c1.gif"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.barTintColor = navigationBarColor;
    _biaozhi=YES;
    //初始化周边商户列表
    _zoubianlist=[NSMutableDictionary dictionaryWithCapacity:10];
    //创建位置管理器
    [self createLocationManager];
    //设置导航栏字体颜色为白色
    self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
    
    //初始化右边的更新按钮
    UIBarButtonItem *customRightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"列表" style:UIBarButtonItemStyleBordered target:self action:@selector(showGuide)];
    self.navigationItem.rightBarButtonItem = customRightBarButtonItem;
    //初始化云检索服务
    _search = [[BMKCloudSearch alloc]init];
    // 设置地图级别
    [_mapView setZoomLevel:18];
    _mapView.isSelectedAnnotationViewFront = YES;
    
    
}



//创建位置管理器及其相关操作
- (void) createLocationManager
{
    
    //1.创建位置管理器
    self.locationManager = [[CLLocationManager alloc] init];
    //指定委托
    self.locationManager.delegate = self;
    //指定所需精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //距离筛选器
    self.locationManager.distanceFilter = 10;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        [self.locationManager requestAlwaysAuthorization];
    }
    
    //启动
    [self.locationManager startUpdatingLocation];
    
    
    //设置定位精确度，默认：kCLLocationAccuracyBest
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:100.f];
    
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    [_locService startUserLocationService];
    
    
    
    
    
    
}


////实现相关delegate 处理位置信息更新
////处理方向变更信息
//- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
//{
//    NSLog(@"heading is %@",userLocation.heading);
//}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    self.lat=  [NSString stringWithFormat:@"%g",  userLocation.location.coordinate.latitude];
    self.log =  [NSString stringWithFormat:@"%g",  userLocation.location.coordinate.longitude];
    //海拔
    self.haiba = [NSString stringWithFormat:@"%g", userLocation.location.verticalAccuracy];
    self.location =userLocation.location;
    //达到100米的位置误差后再次调用周边
    [self onClickNearbySearch];
    
    
}
//定位失败调用
- (void)didFailToLocateUserWithError:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"定位失败，请检查是否有定位权限!" message:[NSString stringWithFormat:@"%@", error] delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
    [alert show];
    
}





//- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
//{
//    //获取当前位置(locations的最后一个元素就是最新位置)
//    CLLocation *location = [locations lastObject];
//
//    NSLog(@"%f,%f",location.coordinate.latitude,location.coordinate.longitude);
//
//    CLLocationCoordinate2D test = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
//    //转换 google地图、soso地图、aliyun地图、mapabc地图和amap地图所用坐标至百度坐标
//    NSDictionary* testdic = BMKConvertBaiduCoorFrom(test,BMK_COORDTYPE_COMMON);
//    //转换GPS坐标至百度坐标
//    testdic = BMKConvertBaiduCoorFrom(test,BMK_COORDTYPE_GPS);
//          test= BMKCoorDictionaryDecode(testdic);
//    NSLog(@"x=%f,y=%f",test.latitude,test.longitude);
//    self.lat=  [NSString stringWithFormat:@"%g",  test.latitude];
//    self.log =  [NSString stringWithFormat:@"%g",  test.longitude];
//    //海拔
//    self.haiba = [NSString stringWithFormat:@"%g", location.verticalAccuracy];
//    self.location = location;
//
//    if (_biaozhi) {
//        [self onClickNearbySearch];
//        _biaozhi=NO;
//    }
//
//
//
//}
//
//- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
//{
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:[NSString stringWithFormat:@"%@", error] delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
//    [alert show];
//}



-(void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden=NO;
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _search.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    //启动LocationService
    [_locService stopUserLocationService];
    _mapView.delegate = nil; // 不用时，置nil
    _search.delegate = nil; // 不用时，置nil
}

- (void)viewDidUnload {
    [super viewDidUnload];
    [self onClickNearbySearch];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
}

- (void)dealloc {
    if (_search != nil) {
        _search = nil;
    }
    if (_mapView) {
        _mapView = nil;
    }
}
//显示说明
-(void)showGuide
{
//    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"开发中" message:@"期待中！！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
//    [myAlertView show];
    
    NSMutableArray * array=[NSMutableArray array];
    
    NSArray * titiles=@[@"全部",@"优惠",@"推荐",@"周边"];
    for (int i=0; i<titiles.count; i++) {
        
        if (i==0) {
            HLTmerchanthomeViewController *nex1= [[HLTmerchanthomeViewController alloc] init];
            //            nex1.type=suoyoutype;
            [array addObject:nex1];
        }
        else if (i==1)
        {
            HLTzhoubiantuijianyouhuimerchantTableViewController *nex1= [[HLTzhoubiantuijianyouhuimerchantTableViewController alloc] init];
            //            nex1.type=tuikuantype;
            
            
            [array addObject:nex1];
            
        }else if (i==2)
        {
            HLTzhoubiantuijianyouhuimerchantTableViewController *nex1= [[HLTzhoubiantuijianyouhuimerchantTableViewController alloc] init];
            //            nex1.type=yiwanchengtype;
            [array addObject:nex1];
        }else if (i==3)
        {
            HLTzhoubiantuijianyouhuimerchantTableViewController *nex1= [[HLTzhoubiantuijianyouhuimerchantTableViewController alloc] init];
            //            nex1.type=daiqueren;
            [array addObject:nex1];
        }
    }
    
    
    SliderViewController * next=[[SliderViewController alloc] initWithViewControllers:array];
    //            next.tag=1005;
    
    
    for (int i=0; i<[array count]; i++) {
        
        if (i==0) {
            HLTmerchanthomeViewController *vcc=array[i];
            vcc.parent=next;
        }
        else if(i==1)
        {
            HLTzhoubiantuijianyouhuimerchantTableViewController *vcc=array[i];
            vcc.shoptye=youhuitype;
            vcc.parent=next;
        }
        else if (i==2)
        {
            HLTzhoubiantuijianyouhuimerchantTableViewController *vcc=array[i];
            vcc.shoptye=tuijiantype;
            vcc.parent=next;
            
        }else if (i==3)
        {
            HLTzhoubiantuijianyouhuimerchantTableViewController *vcc=array[i];
            vcc.shoptye=zoubian;
            vcc.parent=next;
        }
        
        
        
        
    }
    
    
    next.titileArray=titiles;
    next.lineHeight=2;
    next.selectTextColor=RGB(0, 128, 208);
    
    next.selectBgColor=[UIColor whiteColor];
    next.defaultUnSelectBgColor=[UIColor lightGrayColor];
    // next.separateColor=[UIColor redColor];
    next.selectIndex=3;
    next.sliderDelegate=self;
    //    [self.navigationController pushViewController:next animated:YES];
//    self.slider=next;
        next.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:next animated:YES];
    
    
    
    
}

//发起周边云检索
-(void)onClickNearbySearch
{
    BMKCloudNearbySearchInfo *cloudNearbySearch = [[BMKCloudNearbySearchInfo alloc]init];
    cloudNearbySearch.ak = kak;
    cloudNearbySearch.geoTableId = kgeotable_id;
    cloudNearbySearch.pageIndex = 0;
    cloudNearbySearch.pageSize = 100;
    cloudNearbySearch.location =[NSString stringWithFormat:@"%@,%@",_log,_lat];
    cloudNearbySearch.radius = 50000;
    cloudNearbySearch.keyword = @"hlt";
    BOOL flag = [_search nearbySearchWithSearchInfo:cloudNearbySearch];
    if(flag)
    {
        NSLog(@"周边云检索发送成功");
    }
    else
    {
        NSLog(@"周边云检索发送失败");
    }
    
}


#pragma mark -
#pragma mark implement BMKMapViewDelegate
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view
{
//    ShopcontentTableViewController *shopcontent= [ShopcontentTableViewController new];
//    
//    shopcontent.hidesBottomBarWhenPushed=YES;
//    //根据title取出商户数据
//    NSString *keyy= view.annotation.title;
//    //     BMKActionPaopaoView *paopao=view.paopaoView;
//    //     UIView *qq=paopao.subviews[0];
//    NSDictionary *dict=_zoubianlist[keyy];
//    shopcontent.shopcontent=dict;
//    
//    [self.navigationController pushViewController:shopcontent animated:YES];
    
}


/**
 *根据anntation生成对应的View
 *@param mapView 地图View
 *@param annotation 指定的标注
 *@return 生成的标注View
 */
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    // 生成重用标示identifier
    NSString *AnnotationViewID = @"xidanMark";
    
    // 检查是否有重用的缓存
    BMKAnnotationView* annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    
    // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        // 设置重天上掉下的效果(annotation)
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
    
    // 设置位置
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    //根据title取出商户数据
    NSString *keyy= annotation.title;
    NSDictionary *dict=_zoubianlist[keyy];
    custompaopaoview *custompaopao=[[custompaopaoview alloc]initWithFrame:CGRectMake(0, 0, 250, 80)];
    //为自定义的饿uiview赋值
    custompaopao.logourl=dict[@"shopLogo"];
    custompaopao.shopnamestr=dict[@"shopName"];
    custompaopao.shopid=dict[@"id"];
    custompaopao.shoptelstr=dict[@"telephone"];
    custompaopao.shopaddress.text=dict[@"address"];
    //将赋值后的数据初始化
    [custompaopao creat];
    BMKActionPaopaoView *paopao=[[BMKActionPaopaoView alloc] initWithCustomView:custompaopao];
    annotationView.paopaoView=paopao;
    // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
    annotationView.canShowCallout = YES;
    // 设置是否可以拖拽
    annotationView.draggable = NO;
    
    return annotationView;
}
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    [mapView bringSubviewToFront:view];
    [mapView setNeedsDisplay];
}
- (void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    NSLog(@"didAddAnnotationViews");
}

#pragma mark -先搜索出数据，再设置标注
#pragma mark implement BMKSearchDelegate

- (void)onGetCloudPoiResult:(NSArray*)poiResultList searchType:(int)type errorCode:(int)error
{
    // 清楚屏幕中所有的annotation
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    
    if (error == BMKErrorOk) {
        BMKCloudPOIList* result = [poiResultList objectAtIndex:0];
        for (int i = 0; i < result.POIs.count; i++) {
            BMKCloudPOIInfo* poi = [result.POIs objectAtIndex:i];
            //自定义字段
            if(poi.customDict!=nil&&poi.customDict.count>1)
            {
                NSString* customStringField = [poi.customDict objectForKey:@"Telephone"];
                NSLog(@"customFieldOutput=%@",customStringField);
                NSNumber* customDoubleField = [poi.customDict objectForKey:@"Telephone"];
                NSLog(@"customDoubleFieldOutput=%f",customDoubleField.doubleValue);
                
            }
            
            BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
            CLLocationCoordinate2D pt = (CLLocationCoordinate2D){ poi.longitude,poi.latitude};
            item.coordinate = pt;
            //将字典的键作为title，以便在委托中找到内容
            item.title = poi.customDict[@"Shop_id"];
            NSString*string ;
            string = [poi.title substringFromIndex:3];//截取下标2之后的字符串
            
            NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:string,@"shopName",poi.customDict[@"Shop_imgurl"],@"shopLogo",poi.address,@"address",poi.customDict[@"Shop_id"],@"id",poi.customDict[@"Telephone"],@"telephone",poi.tags,@"shoptype",nil];
            //将数据添加到周边列表数组中
            [_zoubianlist setObject:dict forKey:poi.customDict[@"Shop_id"]];
            
            [_mapView addAnnotation:item];
            if(i == 0)
            {
                //将第一个点的坐标移到屏幕中央
                CLLocationCoordinate2D pt1 = (CLLocationCoordinate2D){ [self.lat floatValue],[self.log floatValue]};
                _mapView.centerCoordinate = pt1;
            }
        }
    } else {
        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"您的周围还没有商家！"   message:@"" delegate:nil cancelButtonTitle:@"好" otherButtonTitles: nil];
        [alert show];
        
        
        
        
        NSLog(@"error ==%d",error);
    }
}
- (void)onGetCloudPoiDetailResult:(BMKCloudPOIInfo*)poiDetailResult searchType:(int)type errorCode:(int)error
{
    // 清楚屏幕中所有的annotation
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    
    if (error == BMKErrorOk) {
        BMKCloudPOIInfo* poi = poiDetailResult;
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        CLLocationCoordinate2D pt = (CLLocationCoordinate2D){ poi.longitude,poi.latitude};
        item.coordinate = pt;
        item.title = poi.title;
        [_mapView addAnnotation:item];
        //将第一个点的坐标移到屏幕中央
         CLLocationCoordinate2D pt1 = (CLLocationCoordinate2D){ [self.lat floatValue],[self.log floatValue]};
        _mapView.centerCoordinate = pt;
    } else {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"您的周围还没有商家！"   message:@"" delegate:nil cancelButtonTitle:@"好" otherButtonTitles: nil];
        [alert show];
        NSLog(@"error ==%d",error);
    }
}






#pragma mark slider的委托

-(void)sliderScrollerDidIndex:(NSInteger)index andSlider:(SliderViewController *)slider{
    
    NSString * tiitle=slider.titileArray[index];
    slider.title=tiitle;
}




@end
